package io.file;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Nullable;

import org.apache.commons.io.FileUtils;
import org.testng.annotations.Test;

/**
 *
 * 2 获取文件总行数的快捷方式
 *
 * @author topjoy
 */
public class FileIO1 {

    @Test
    private void t1() {

        new FileIO1()
            .outPrint(null);

    }

    @Test
    private void t2() throws IOException {
        String filePath = "/Users/topjoy/Documents/LBData.txt";

        long totalLineNum = Files.lines(Paths.get(filePath)).count();
        System.out.println(totalLineNum);
    }

    @Test
    public void getAllFileNameFromAMenu() {
        // 目录里只有文件
        String menu = "D:\\wzcq2\\Data\\Branch\\TiaoShiServer\\table\\serverData";

        // 目录里含有目录，并不会得到二级目录里的文件名
        String menu2 = "D:\\wzcq\\Data\\Branch\\CurrentUseData\\Normal\\data";



        File directory = new File(menu);



        if (directory.exists() && directory.isDirectory()) {
            String[] files = directory.list();
            for (String s : files) {
                System.out.println(s);
            }
        }




    }

    public List<String> getName(String menu) {

        File directory2 = new File(menu);
        List<String> dataNames = new ArrayList<>();
        if (directory2.exists() && directory2.isDirectory()) {
            String[] files = directory2.list();
            assert files != null;
            dataNames.addAll(Arrays.asList(files));
        }
        return dataNames;
    }

    public List<String> removeNamePostfix(List<String> list) {
        return list.stream()
                .map(name -> {
                    if (name.contains(".")) {
                        return name.substring(0, name.lastIndexOf("."));
                    } else {
                        return name;
                    }
                })
                .collect(Collectors.toList());
    }

    public void check_Name(List<String> list) {
        list.forEach(name -> {
                    if (!name.contains("_")) {
                        System.out.println(name);
                    }
                });
    }

    @Test
    public void replaceFileContext() {
        String menuInWangZheData = "D:\\wzcq\\Data\\Branch\\CurrentUseData\\Normal\\data";
        List<String> configNameList = removeNamePostfix(getName(menuInWangZheData));
        System.out.println(configNameList);

        //
        String menuInNew = "D:\\mu\\muwangzhe2\\mu-basic\\src\\main\\java\\com\\sh\\mu\\basic\\etc\\data\\model";
        String menuInNewProj = "D:\\wzcq2\\Data\\Branch\\TiaoShiServer\\table\\serverData";
        check_Name(getName(menuInNewProj));

        File directory3 = new File(menuInNew);

        if (directory3.exists() && directory3.isDirectory()) {
//            Arrays.stream(directory3.list()).forEach(System.out::println);
            File[] files = directory3.listFiles();
            assert files != null;
            for (File file : files) {

                try (FileInputStream fis = new FileInputStream(file);
                     InputStreamReader isr = new InputStreamReader(fis);
                     BufferedReader br = new BufferedReader(isr)) {

                    int i = 0;
                    String line;
                    while ((line = br.readLine()) != null && i < 30) {
                        i++;
                        if (line.startsWith("@ConfigData")) {
                            line = line.replace("@ConfigData", "//@ConfigData");
//                            System.out.println(line);
                            int first = line.indexOf("\"");
                            if (first != -1) {
                                int second = line.indexOf("\"", first + 1);
                                if (second != -1) {
                                    // 前闭后开区间
                                    String configName = line.substring(first + 1, second);
//                                    System.out.println(configName);
                                    if (!configNameList.contains(configName)) {
//                                        System.out.println(configName);
                                    }
                                }

                            }
                        }

                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    @Test
    public void replaceText() throws IOException {
        String menuInNew = "D:\\mu\\muwangzhe2\\mu-basic\\src\\main\\java\\com\\sh\\mu\\basic\\etc\\data\\model";
        File directory = new File(menuInNew);
        int m = 0;

        int n = 0;
        List<String> configInServerData2 = (List<String>) this.t3();

        for (String name : directory.list()) {
            Path path = Paths.get(menuInNew + "\\" + name);
            List<String> allLines = Files.readAllLines(path);
            String content = String.join(System.lineSeparator(), allLines);
            String[] split = content.split(System.lineSeparator());
            for (int i = 0; i < split.length; i++) {
                if (split[i].startsWith("//@ConfigData")) {
                    String[] innerName = split[i].split("\"");
                    if (!configInServerData2.contains(innerName[1])) {
                        System.out.println(innerName[1]);
                        n++;
//                        split[i] = "//" + split[i];
                        split[i] = split[i].replace("//@ConfigData", "@ConfigData");
                    }

//                    System.out.println(split[i]);
//                    split[i] = split[i].replace("//@ConfigData", "@ConfigData");
                }
            }

            // 有三分之二的model类末尾有空行，剩下三分之一末尾没有空行，这就会导致三分之一额外加上一个空行
            String modifiedContent = String.join(System.lineSeparator(), split) + System.lineSeparator();
//            if (modifiedContent.endsWith("}" + System.lineSeparator())) {
//                System.out.println(modifiedContent);
//            }
//            String modifiedContent = String.join(System.lineSeparator(), split);
            // 写文件
            Files.write(path, modifiedContent.getBytes());

            // 循环次数控制
//            m++;
//            if (m > 5) {
//                break;
//            }
        }

        System.out.println("configInServerData2 " + configInServerData2.size());
        System.out.println("cant match number " + n);
    }


    /**
     * 查找数值表中的配表名称
     */
    public List<? extends String> t3() throws IOException {
        String menuInNew = "D:\\wzcq2\\Data\\Branch\\TiaoShiServer\\table\\serverData2";
        File directory = new File(menuInNew);

        List<String> nameList = new ArrayList<>();
        for (String name : directory.list()) {
            String[] split = name.split("\\.");
            nameList.add(split[0]);

//            Path path = Paths.get(menuInNew + "\\" + name);
//            List<String> allLines = Files.readAllLines(path);
//            String content = String.join(System.lineSeparator(), allLines);
//            String[] split = content.split(System.lineSeparator());
//            for (int i = 0; i < split.length; i++) {
//                if (split[i].startsWith("@ConfigData")) {
//                    split[i] = "//" + split[i];
//                    System.out.println(split[i]);
//                    split[i] = split[i].replace("//@ConfigData", "@ConfigData");
//                }
//            }

        }

        return nameList;
    }

    @Test(description = "查找指定字符")
    public void searchSpecialContent() throws IOException {
        String menuInNew = "D:\\wzcq\\Data\\Branch\\CurrentUseData\\Normal\\xml";
        String target = "LevelSeal";
        File directory = new File(menuInNew);
        int m = 0;
        for (String name : Objects.requireNonNull(directory.list())) {
            Path path = Paths.get(menuInNew + "\\" + name);
            List<String> allLines = Files.readAllLines(path);
            String content = String.join(System.lineSeparator(), allLines);
            String[] split = content.split(System.lineSeparator());
            for (int i = 0; i < split.length; i++) {
                if (split[i].compareToIgnoreCase("LevelSeal") == 0) {
                    System.out.println(name);
                    System.out.println(split[i]);
                }
                if (split[i].contains(target)) {
                    System.out.println(name);
                    System.out.println(split[i]);
                }
            }

            if (m > 10) {
                break;
            }

        }



    }





    public static void main(String[] args) {
        new FileIO1()
            .outPrint(null);
    }


    public void outPrint(Param s) {
        System.out.println(s);
    }


    class Param {

        private int a;

        public Param(int a) {
            this.a = a;
        }
    }



}
